package com.example.itshome.network;

import android.app.Activity;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.itshome.entity.CircleEntity;
import com.example.itshome.manager.UserInfoManager;
import com.zhpan.bannerview.constants.PageStyle;
import org.json.JSONException;
import org.json.JSONObject;

public class GiveLikeRequest extends AbstractNetworkRequest{
    private ImageView likeImageView;
    private TextView likeCountTextView;
    private CircleEntity entity;
    private boolean isPass=false;

    public GiveLikeRequest setEntity(CircleEntity entity) {
        this.entity = entity;
        return this;
    }

    public GiveLikeRequest setLikeImageView(ImageView likeImageView) {
        this.likeImageView = likeImageView;
        return this;
    }

    public GiveLikeRequest setLikeCountTextView(TextView likeCountTextView) {
        this.likeCountTextView = likeCountTextView;
        return this;
    }

    public GiveLikeRequest(Activity activity) {
        super(activity);
    }

    @Override
    protected String getPathAndParams() {
        if(entity.isLiked()){
            return "moment/dislike?username="+ UserInfoManager.getInstance().getUser().getUsername()+
                    "&id="+entity.getId();
        }
        return "moment/like?username="+ UserInfoManager.getInstance().getUser().getUsername()+
                "&id="+entity.getId();
    }

    @Override
    protected void handleResult(String result) {
        try {
            JSONObject jsonObject=new JSONObject(result);
            int code =jsonObject.getInt("code");
            try {
                if(!isPass&&!jsonObject.getBoolean("data")){
                    isPass=true;
                    entity.setLiked(!entity.isLiked());
                    start();
                }
            }catch (JSONException e){
                e.printStackTrace();
            }
            if(code!=200) {
                return;
            }
            if (isPass){
                entity.setLiked(!entity.isLiked());
                return;
            }

            setHandleResultRunnable(new Runnable() {
                @Override
                public void run() {
                    entity.setLiked(!entity.isLiked());
                    entity.setLikeCount(String.valueOf(Integer.parseInt(likeCountTextView.getText().toString())+(entity.isLiked()?1:-1)));
                    likeImageView.setSelected(entity.isLiked());
                    likeCountTextView.setText(entity.getLikeCount());
                }
            });
        }catch (JSONException e){
            e.printStackTrace();
        }
    }
}
